package com.im.utils.Redis.RedisBatch;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class RedisScriptManager {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private String scriptSha;

    public String getScriptSha() {return scriptSha;}

    // 修改后的 Lua 脚本：使用 INCR 实现序列号生成，不再使用 ZSET 和 INFO
    private static final String LUA_SCRIPT =
            "local key = KEYS[1]\n" +
                    "local timeKey = key .. ':time'\n" +
                    "local seqKey = key .. ':seq'\n" +
                    "local now = tonumber(redis.call('TIME')[1])\n" +
                    "local lastTime = tonumber(redis.call('GET', timeKey) or 0)\n" +
                    "local seq = 0\n" +
                    "if lastTime == now then\n" +
                    "    seq = redis.call('INCR', seqKey)\n" +
                    "else\n" +
                    "    redis.call('SET', timeKey, now)\n" +
                    "    redis.call('SET', seqKey, 1)\n" +
                    "    seq = 1\n" +
                    "end\n" +
                    "return now * 1000000 + seq";

    @PostConstruct
    public void loadScript() {
        // 将 Lua 脚本预加载到 Redis 中，获取 SHA1 标识
        scriptSha = redisTemplate.execute((connection) ->
                        connection.scriptLoad(LUA_SCRIPT.getBytes(StandardCharsets.UTF_8)),
                true);
        System.out.println("Lua 脚本已加载，SHA1: " + scriptSha);
    }
}
